import { useCallback, useMemo, useState, ReactElement, useRef } from 'react';
import { Button, Space, Popconfirm, message } from 'antd';
import {
  EditOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  MinusCircleOutlined,
  HolderOutlined,
} from '@ant-design/icons';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { TextWidget, getMessage } from '@inbiz/react';
import { arrayMoveImmutable } from 'array-move';
import { useForm } from '@formily/react'
import { AddIndexRange } from './addIndexRange'; // 添加索引范围
import { DmsSetting } from './DmsSetting'; // dms设置弹窗
import './index.less';

type IDatasource = {
  title: string;
  isEdit: any;
  isShow: any;
  isDelete: any;
  guid: string | number;
}[];

const DragHandle = SortableHandle(() => <HolderOutlined />) as unknown as () => ReactElement;
const SortableItem = SortableElement(
  ({
    item,
    idx,
    handelEdit,
    updateHide,
    handleDel,
  }: {
    item: IDatasource[number];
    idx: number;
    handelEdit: (item: IDatasource[number]) => void;
    updateHide: (idx: number) => void;
    handleDel: (guid: number | string) => void;
  }) => {
    return (
      <div className="list-item" key={idx}>
        <div className="list-item-title">
          <TextWidget>{item.title}</TextWidget>
        </div>
        <div className="hendle-box">
          <Space>
            {item.isEdit && <EditOutlined onClick={() => handelEdit(item)} />}
            {item.isShow ? (
              <EyeOutlined onClick={() => updateHide(idx)} />
            ) : (
              <EyeInvisibleOutlined onClick={() => updateHide(idx)} />
            )}
            {item.isDelete && (
              <Popconfirm
                title={getMessage('SearchEngine.tips.areYouSureYouWantToDelete')}
                onConfirm={() => handleDel(item.guid)}
                okText={getMessage('SearchEngine.determine')}
                cancelText={getMessage('SearchEngine.cancel')}
                placement="right"
              >
                <MinusCircleOutlined />
              </Popconfirm>
            )}
            <DragHandle />
          </Space>
        </div>
      </div>
    );
  },
);

const SortableList = SortableContainer(
  ({
    datasource,
    ...other
  }: {
    datasource: IDatasource;
    handelEdit: (item: IDatasource[number]) => void;
    updateHide: (idx: number) => void;
    handleDel: (guid: number | string) => void;
  }) => {
    return (
      <div>
        {datasource.map((item, index) => {
          //@ts-ignore
          return (
            <SortableItem
              idx={index}
              index={index}
              item={item}
              key={item.guid + '_' + index}
              {...other}
            />
          );
        })}
      </div>
    );
  },
);

const IndexSetting = (props: any) => {
  const { onChange, value } = props;
  // 列表数据
  const [datasource, $datasource] = useState<IDatasource>(value);
  // 添加索引范围弹窗可见
  const [indexRangeVisible, $indexRangeVisible] = useState(false);
  // 编辑当前索引范围的数据
  const [currentData, $currentData] = useState<object>({});
  // dms设置弹窗可见
  const [dmsSettingVisible, $dmsSettingVisible] = useState(false);
  const form = useForm()

  // 删除当前数据-ok
  const handleDel = useCallback(
    (guid: string | number) => {
      const arr = datasource.filter((item) => item.guid !== guid);
      $datasource(arr);
      onChange?.(arr);
    },
    [datasource, onChange],
  );

  // 编辑当前数据
  const handelEdit = (record: any) => {
    if (record?.isDMS || record?.isFile || record?.isFolder) {
      // 编辑文档标签
      let nr: any = record.customRange
        ? record
        : { ...record, customRange: ['allFolder', 'curfolder'] };
      $currentData({ ...nr, viewType: form?.values['x-component-props'].viewType });
      $dmsSettingVisible(true);
    } else {
      $currentData({ ...record, viewType: form?.values['x-component-props'].viewType });
      $indexRangeVisible(true);
    }
  };

  // 切换显示隐藏-ok
  const updateHide = useCallback(
    (index: number) => {
      let arr = [...datasource];
      arr[index] = {
        ...arr[index],
        isShow: !arr[index].isShow,
      };
      if (arr.some((item) => item.isShow)) {
        $datasource(arr);
        props.onChange(arr);
      } else {
        message.warning(getMessage('SearchEngine.tips.selectAtLeastOneDisplayedLabel'));
      }
    },
    [datasource, props.onChange],
  );

  // 添加索引范围
  const mlAdd = () => {
    $indexRangeVisible(true);
    $currentData({
      searchMode: false,
      viewType: form?.values['x-component-props'].viewType,
      advancedSearch: false,
    });
  };

  // 添加索引范围弹窗取消事件
  const onIndexRangeCancel = () => {
    $indexRangeVisible(false);
  };

  // 添加索引范围弹窗保存事件
  const onIndexRangeOk = useCallback(
    (values) => {
      let arr = [...datasource];
      const isExist = arr.filter((item) => item?.guid == values.guid);
      // 判断是新增还是编辑
      if (isExist.length) {
        // 编辑
        let idx: number = -1;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].guid === values.guid) {
            idx = i;
          }
        }
        arr[idx] = { ...values };
      } else {
        // 新增

        arr.push({
          ...values,
          isEdit: true,
          isDelete: true,
          isShow: true,
        });
      }
      $datasource(arr);
      props.onChange(arr);
      $indexRangeVisible(false);
    },
    [datasource, props.onChange],
  );

  // 添加索引范围配置参数
  const AddIndexRangeProps = {
    visible: indexRangeVisible, // 可见
    onCancel: onIndexRangeCancel, // 取消事件
    onOk: onIndexRangeOk, // 保存事件
    currentData: currentData, // 传递的表单值
  };

  // 添加索引范围组件
  const AddIndexRangeComponent = useMemo(
    () => indexRangeVisible && <AddIndexRange {...AddIndexRangeProps} />,
    [indexRangeVisible],
  );



  // dms设置弹窗组件取消事件
  const onDmsSettingCancel = () => {
    $dmsSettingVisible(false);
  };

  // dms设置弹窗组件保存事件

  const onDmsSettingOk = useCallback(
    (values) => {
      let arr = [...datasource];
      let idx: number = -1;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].guid === values.guid) {
          idx = i;
        }
      }
      arr[idx] = { ...values };
      $datasource(arr);
      props.onChange(arr);
      $dmsSettingVisible(false);
    },
    [datasource, props.onChange],
  );

  // dms设置弹窗组件配置参数
  const dmsSettingProps = {
    visible: dmsSettingVisible, // 可见
    onCancel: onDmsSettingCancel, // 取消事件
    onOk: onDmsSettingOk, // 保存事件
    currentData: currentData, // 传递的表单值
  };
  // dms设置弹窗组件
  const dmsSettingComponent = useMemo(
    () => dmsSettingVisible && <DmsSetting {...dmsSettingProps} />,
    [dmsSettingVisible, props.onChange],
  );

  const handleSortEnd = useCallback(
    ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
      $datasource((list) => {
        const newList = arrayMoveImmutable(list, oldIndex, newIndex);
        onChange?.(newList);
        return newList;
      });
      $helperBoxClass('');
    },
    [onChange],
  );
  const $ul: any = useRef(null);
  const [helperBoxClass, $helperBoxClass] = useState('');
  return (
    <div className="search-dynamc-main-box">
      <div className={`dynamc-main ${helperBoxClass}`}>
        {/* @ts-ignore */}
        <SortableList
          datasource={datasource}
          handelEdit={handelEdit}
          updateHide={updateHide}
          handleDel={handleDel}
          useDragHandle
          onSortEnd={handleSortEnd}
          ref={$ul}
          helperContainer={() => $ul.current?.container}
          helperClass="helper"
          onSortStart={() => $helperBoxClass('helpering')}
        />
        <Button style={{ marginTop: '10px' }} onClick={mlAdd}>
          <TextWidget>SearchEngine.addTo</TextWidget>
        </Button>
      </div>
      {AddIndexRangeComponent}
      {dmsSettingComponent}
    </div>
  );
};

export default IndexSetting;
